var statistic = angular.module('statistic', ['ngRoute']);

function serialize(obj) {
	var str = [];
	for (var p in obj)
		str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
	return str.join("&");
};

statistic.filter('cut', function () {
  return function (value, wordwise, max, tail) {
    if (!value) return '';

    max = parseInt(max, 10);
    if (!max) return value;
    if (value.length <= max) return value;

    value = value.substr(0, max);
    if (wordwise) {
      var lastspace = value.lastIndexOf(' ');
      if (lastspace != -1) {
        value = value.substr(0, lastspace);
      }
    }

    return value + (tail || ' …');
  };
});

statistic.config(['$routeProvider','$interpolateProvider', '$locationProvider', function($routeProvider, $interpolateProvider, $locationProvider) {
    $routeProvider
	.when('/',{
		templateUrl:"/static/views/wb_info.html",
		controller:"ctl_wb_info"
	})
    .when('/status_record', {
        templateUrl: '/static/views/status_record.html',
        controller: 'ctl_status_record'
    })
    .when('/interact_record', {
        templateUrl: '/static/views/interact_record.html',
        controller: 'ctl_interact_record'
    })
	.when('/wb_data',{
		templateUrl:'/static/views/wb_manage/wb_data.html',
		controller:'ctl_wb_data'
	})
	.when('/wb_location',{
		templateUrl:'/static/views/wb_manage/wb_location.html',
		controller:'ctl_wb_location'
	})
	.when('/wb_sos',{
		templateUrl:'/static/views/wb_manage/wb_sos.html',
		controller:'ctl_wb_sos'
	})
	.when('/user_info',{
		templateUrl:'/static/views/user_manage/users_info.html',
		controller:'ctl_user_info'
	})
	.when('/modify_password',{
		templateUrl:'/static/views/modify_password.html',
		controller:'ctl_modify_password'
	})
    .otherwise({
        templateUrl: '/static/views/status_record.html',
        controller: 'ctl_status_record'
    });

    $locationProvider.html5Mode({
         enabled: true,
         requireBase: false
    });

    $interpolateProvider.startSymbol('{[');
    $interpolateProvider.endSymbol(']}');
}]);

statistic.controller('main_container', function($scope, $rootScope, $http) {
    $scope.$on('active',function(event,name,page_name){
        $scope.ctl_name = name;
		$scope.page_name = page_name;
    });
	$scope.logout = function(){
		$http.post('/v1/logout').success(function(data){
			location = '/';
		});
	}
});


function JumpPage(scope){
    if(!scope.getRecords){
        throw Error('$scope undefinition "getRecords" Method before jumpPage');
    }
    if(!scope.numlist) scope.numlist = [10,20,30];
    if(!scope._paginateTotal) scope._paginateTotal = 10;
    if(!scope.length) scope.length = 0;
    if(!scope.num) scope.num = scope.numlist[0];
    if(!scope.pagelist) scope.pagelist = new Array();
    if(!scope.current_page) scope.current_page = 1;

    return function(page){
        var k = 0;
        for(var i=0;i<scope.pagelist.length;i++){
            if(page == scope.pagelist[i]) k = 1;
        }
        var ignore = 0;
        if(!k && page == 1){
            var a = new Array();
            for(var i=0;i<this._paginateTotal;i++){
                if(i >= scope.totalPage) break;
                a.push(i+1);
            }
            scope.pagelist = a;
            ignore = 1;
        }
        if(!k && page == scope.totalPage){
            var a = new Array();
            for(var i=0;i<this._paginateTotal;i++){
                var value = scope.totalPage-i;
                if(value <= 0) break;
                a.unshift(value);
            }
            scope.pagelist = a;
            ignore = 1;
        }
        if(!ignore && !k && page < scope.pagelist[0]){
            var a = new Array();
            var last = scope.pagelist[0]-1;
            for(var i=0;i<this._paginateTotal;i++){
                var value = last-i;
                if(value <= 0) break;
                a.unshift(value);
            }
            scope.pagelist = a;
        }
        if(!ignore && !k && page > scope.pagelist[scope.pagelist.length-1]){
            var a = new Array();
            var first = scope.pagelist[scope.pagelist.length-1]+1;
            for(var i=0;i<this._paginateTotal;i++){
                var value = first+i;
                if(value > scope.totalPage) break;
                a.push(value);
            }
            scope.pagelist = a;
        }
        scope.current_page = page;
        scope.getRecords();
    };
};

statistic.controller('ctl_status_record', function($scope, $rootScope, $http) {
    $scope.$emit("active", 'ctl_status_record','上下线记录');

    $scope.searchRecords = function(){
        $http.get('/v1/status_record_length',{params:{imei:$scope.imei}}).success(function(data){
            $scope.length = parseInt(data);
            $scope.totalPage = Math.ceil($scope.length/$scope.num);
            var a = new Array();
            for(var i=1;i<$scope.totalPage+1;i++){
                a.push(i);
                if(i >= 10) break;
            }
            $scope.pagelist = a;
        });
        $scope.current_page = 1;
        $scope.getRecords();
    };

    $scope.getRecords = function(){
        $http.get('/v1/status_record',{params:{imei:$scope.imei,page:$scope.current_page-1,num:$scope.num}}).success(function(data){
            $scope.records = data;
        });
    };

    $scope.jumpPage = JumpPage($scope);
});

statistic.controller('ctl_interact_record', function($scope, $rootScope, $http) {
    $scope.$emit("active", 'ctl_interact_record','发送/接受记录');

    $scope.searchRecords = function(){
        $http.get('/v1/interact_record_length',{params:{imei:$scope.imei}}).success(function(data){
            $scope.length = parseInt(data);
            $scope.totalPage = Math.ceil($scope.length/$scope.num);
            var a = new Array();
            for(var i=1;i<$scope.totalPage+1;i++){
                a.push(i);
                if(i >= 10) break;
            }
            $scope.pagelist = a;
        });
        $scope.current_page = 1;
        $scope.getRecords();
    };

    $scope.getRecords = function() {
        $http.get('/v1/interact_record',{params:{imei:$scope.imei,page:$scope.current_page-1,num:$scope.num}}).success(function(data){
        $scope.records = data;
     });
    };

    $scope.jumpPage = JumpPage($scope);
});

statistic.controller('ctl_wb_data',function($scope,$rootScope,$http){
	$scope.$emit("active", 'ctl_wb_data','腕表数据');
	$scope.show_chart = false;
	var step_list = new Array();
	var distance_list = new Array();
	var calories_list = new Array();
	var time_list = new Array();
	var chart_list = [];
	
	chart_list['step_chart'] = echarts.init(document.getElementById('step_chart'));
	chart_list['distance_chart'] = echarts.init(document.getElementById('distance_chart'));
	chart_list['calories_chart'] = echarts.init(document.getElementById('calories_chart'));
	
    $scope.searchRecords = function(){
        $http.get('/v1/wb_data_length',{params:{imei:$scope.imei}}).success(function(data){
            $scope.length = parseInt(data);
			
            $scope.totalPage = Math.ceil($scope.length/$scope.num);
            var a = new Array();
            for(var i=1;i<$scope.totalPage+1;i++){
                a.push(i);
                if(i >= 10) break;
            }
            $scope.pagelist = a;
        });
        $scope.current_page = 1;
        $scope.getRecords();
    };
	
    $scope.getRecords = function(){
        $http.get('/v1/wb_data',{params:{imei:$scope.imei,page:$scope.current_page-1,num:$scope.num}}).success(function(data){
            $scope.datas = data;
			if(data){
				$scope.has_data = true;
			}else{
				$scope.has_data = false;
			}
			for(i = 0; i < data.length; i++){
				step_list[i] = data[i].step;
				distance_list[i] = data[i].distance;
				calories_list[i] = data[i].calories;
				time_list[i] = data[i].time;
			}
        });
    };
	
	$scope.exchange = function(){
		$scope.show_chart = !$scope.show_chart;	
		chartUpdate('step_chart',time_list,step_list);
		chartUpdate('distance_chart',time_list,distance_list);
		chartUpdate('calories_chart',time_list,calories_list);
	}
	
    $scope.jumpPage = JumpPage($scope);	
	
	var chartUpdate = function(chart_id,x_data,y_data){
        var option = {
			tooltip : {
				show:true
			},
        	xAxis : [
             			{
                            type : 'category',
                            data : x_data
                        }
                    ],
            yAxis : [
                        {
                            type : 'value'
                        }
                    ],
             series : [
                        {
                            "type":"line",
                            "data":y_data
                        }
                    ]
        };
		chart_list[chart_id].clear();
		chart_list[chart_id].setOption(option);
	}
	
});

statistic.controller('ctl_wb_location',function($scope,$rootScope,$http){
	$scope.$emit('active','ctl_wb_location','腕表定位');
	
    $scope.searchRecords = function(){
        $http.get('/v1/wb_location_length',{params:{imei:$scope.imei}}).success(function(data){
            $scope.length = parseInt(data);
            $scope.totalPage = Math.ceil($scope.length/$scope.num);
            var a = new Array();
            for(var i=1;i<$scope.totalPage+1;i++){
                a.push(i);
                if(i >= 10) break;
            }
            $scope.pagelist = a;
        });
        $scope.current_page = 1;
        $scope.getRecords();
    };

    $scope.getRecords = function(){
        $http.get('/v1/wb_location',{params:{imei:$scope.imei,page:$scope.current_page-1,num:$scope.num}}).success(function(data){
            $scope.datas = data;
			if(data && data != ''){
				$scope.has_data = true;
				$scope.position = new Array();
				for(i = 0; i < data.length; i++){
					$scope.position.push(new AMap.LngLat(data[i].lon,data[i].lat));
				}
			}else{
				$scope.has_data = false;
			}
        });
    };

    $scope.jumpPage = JumpPage($scope);
	
	$scope.AMapId='container';//定义地图容器id
	$scope.initAMap=function(){//初始化高德地图
		if($scope.has_data){
			$scope.mapObj=new AMap.Map($scope.AMapId,{
				view:new AMap.View2D({
					center:$scope.position[0],
					zoom:14,
					rotation:0//旋转0
				}),
				lang:'zh_cn'//中文地图
			});	
		}
	}
	
	$scope.addOneMarker = function (PositionIndex) {
		icon_url = (PositionIndex < 10)? "http://webapi.amap.com/images/"+
					(PositionIndex+1)+".png":"http://webapi.amap.com/images/0.png";
		var marker = new AMap.Marker({
			//将点添加到地图
			map: $scope.mapObj,
			position: $scope.position[PositionIndex],
			//marker图标，直接传递地址url
			icon: icon_url,
			offset: new AMap.Pixel(-10, -35)
		});

		var info = [];
		info.push("<b>" + $scope.datas[PositionIndex].address + "</b>");
		info.push("定位时间:" + $scope.datas[PositionIndex].time);

		var infoWindow = new AMap.InfoWindow({
			offset: new AMap.Pixel(0, -23),
			content: info.join("<br>")
		});

		AMap.event.addListener(marker, "click", function (e) {
			infoWindow.open($scope.mapObj, marker.getPosition());
			this.setzIndex(0);
		});
	}
	
	$scope.showSpecifyMarker = function(){
		if($scope.has_data){
			if($scope.pIndex){
				$scope.addOneMarker($scope.pIndex);	
			}else{
				$scope.addOneMarker(0);
			}	
		}
	}
	
	$scope.specifyMarker = function(pIndex){
		$scope.pIndex = pIndex;
		$scope.show_map = !$scope.show_map;
	}	
});

statistic.controller('ctl_wb_sos',function($scope,$rootScope,$http){
	$scope.$emit("active","ctl_wb_sos",'腕表SOS记录');
	
    $scope.searchRecords = function(){
        $http.get('/v1/wb_sos_length',{params:{imei:$scope.imei}}).success(function(data){
            $scope.length = parseInt(data);

            $scope.totalPage = Math.ceil($scope.length/$scope.num);
            var a = new Array();
            for(var i=1;i<$scope.totalPage+1;i++){
                a.push(i);
                if(i >= 10) break;
            }
            $scope.pagelist = a;
        });
        $scope.current_page = 1;
        $scope.getRecords();
    };

    $scope.getRecords = function(){
        $http.get('/v1/wb_sos',{params:{imei:$scope.imei,page:$scope.current_page-1,num:$scope.num}}).success(function(data){
            $scope.datas = data;
			if(data && data != ''){
				$scope.has_data = true;
				$scope.position=new AMap.LngLat(data[0].lon,data[0].lat);
			}else{
				$scope.has_data == false;
			}
        });
    };

    $scope.jumpPage = JumpPage($scope);	
	
	$scope.AMapId='SOSMap_container';//定义地图容器id
	$scope.initAMap=function(){//初始化高德地图
		$scope.mapObj=new AMap.Map($scope.AMapId,{
			view:new AMap.View2D({
				center:$scope.position,
				zoom:14,
				rotation:0//旋转0
			}),
			lang:'zh_cn'//中文地图
		});
	}
	
	$scope.addOneMarker = function (PositionIndex) {
		icon_url = (PositionIndex < 10)? "http://webapi.amap.com/images/"+
					(PositionIndex+1)+".png":"http://webapi.amap.com/images/0.png";
		var marker = new AMap.Marker({
			//将点添加到地图
			map: $scope.mapObj,
			position: $scope.position[PositionIndex],
			//marker图标，直接传递地址url
			icon: icon_url,
			offset: new AMap.Pixel(-10+PositionIndex*2, -35)
		});

		var info = [];
		info.push("<b>" + $scope.datas[PositionIndex].address + "</b>");
		info.push("定位时间:" + $scope.datas[PositionIndex].time);

		var infoWindow = new AMap.InfoWindow({
			offset: new AMap.Pixel(0, -23),
			content: info.join("<br>")
		});

		AMap.event.addListener(marker, "click", function (e) {
			infoWindow.open($scope.mapObj, marker.getPosition());
			this.setzIndex(0);
		});
	}
	
	$scope.showSpecifyMarker = function(){
		if($scope.has_data){
			if($scope.pIndex){
				$scope.addOneMarker($scope.pIndex);	
			}else{
				$scope.addOneMarker(0);
			}	
		}
	}
	
	$scope.specifyMarker = function(pIndex){
		$scope.pIndex = pIndex;
		$scope.show_map = !$scope.show_map;
	}
});

statistic.controller('ctl_wb_info',function($scope,$rootScope,$http){
	$scope.$emit("active","ctl_wb_info");
	
    $scope.searchRecords = function(){
        $http.get('/v1/wb_info_length').success(function(data){
            $scope.length = parseInt(data);

            $scope.totalPage = Math.ceil($scope.length/$scope.num);
            var a = new Array();
            for(var i=1;i<$scope.totalPage+1;i++){
                a.push(i);
                if(i >= 10) break;
            }
            $scope.pagelist = a;
        });
        $scope.current_page = 1;
        $scope.getRecords();
    };

    $scope.getRecords = function(){
        $http.get('/v1/wb_info',{params:{page:$scope.current_page-1,num:$scope.num}}).success(function(data){
            $scope.datas = data;
        });
    };

    $scope.jumpPage = JumpPage($scope);	
});

statistic.controller('ctl_user_info',function($scope,$rootScope,$http){
	$scope.$emit("active","ctl_user_info",'用户管理');
	
    $scope.searchRecords = function(){
        $http.get('/v1/user_info_length').success(function(data){
            $scope.length = parseInt(data);

            $scope.totalPage = Math.ceil($scope.length/$scope.num);
            var a = new Array();
            for(var i=1;i<$scope.totalPage+1;i++){
                a.push(i);
                if(i >= 10) break;
            }
            $scope.pagelist = a;
        });
        $scope.current_page = 1;
        $scope.getRecords();
    };

    $scope.getRecords = function(){
        $http.get('/v1/user_info',{params:{page:$scope.current_page-1,num:$scope.num}}).success(function(data){
            $scope.datas = data;
        });
    };

    $scope.jumpPage = JumpPage($scope);	
});

statistic.controller('ctl_modify_password', function ($scope, $rootScope, $http) {
	$scope.$emit("active", "ctl_modify_password", "修改密码");
	$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

	var show_alert = function (msg, type) {
		$("#modal_alert_text").text(msg);
		$("#modal_alert_button").removeClass().addClass("btn btn-" + type);
		$("#modal_alert").modal();
	};
	
	$scope.password_keydown = function(event){
		if(event.keyCode == 13){
			$scope.modify_confirm();
		}
	}

	$scope.modify_confirm = function () {
		if ($scope.password && $scope.new_password && $scope.new_password_confirm) {
			if($scope.new_password == $scope.new_password_confirm){
				$http.post('/v1/modify_password', serialize({
					'password': hex_md5($scope.password),
					'new_password': hex_md5($scope.new_password)
				})).success(function (data) {
					if (data == 'ok') {
						show_alert('修改成功!', 'success');
						$scope.new_password = '';
						$scope.password = '';
						$scope.new_password_confirm='';
					} else {
						show_alert('密码错误', 'danger');
						$scope.new_password = '';
						$scope.password = '';
						$scope.new_password_confirm='';
					}
				});	
			} else {
				show_alert('两次输入密码不一致','danger');
			}
		} else {
			show_alert("请填写完整信息", 'danger');
		}
	}
});